package java_test_work2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Test {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		UserStorage userStorage = UserStorage.getInstance(); // 获取用户存储实例
		User loggedInUser = null; // 当前登录用户
		boolean exit = false; // 控制循环退出
		while (!exit) {
			System.out.println("1. 注册");
			System.out.println("2. 登录");
			System.out.println("0. 退出");
			System.out.print("请选择一个选项：");
			int initialChoice = input.nextInt();
			switch (initialChoice) {
			case 1:
				// Register a new user
				System.out.print("请输入用户名：");
				String regUsername = input.next();
				System.out.print("请输入密码：");
				String regPassword = input.next();
				System.out.print("请输入个人ID：");
				String regPersonID = input.next();
				System.out.print("请输入电话号码：");
				String regPhoneNumber = input.next();

				User newUser = new Student(regUsername, regPassword, regPersonID, regPhoneNumber);
				userStorage.registerUser(newUser);
				System.out.println("注册成功！");
				break;
			case 2:
				// Login
				System.out.print("请输入用户名：");
				String username = input.next();
				System.out.print("请输入密码：");
				String password = input.next();
				loggedInUser = userStorage.login(username, password);
				if (loggedInUser != null) {
					System.out.println("登录成功！");
					handleUserActions(loggedInUser, input);
				} else {
					System.out.println("用户名或密码错误！");
				}
				break;
			case 0:
				exit = true;
				break;
			default:
				System.out.println("选项无效，请重新输入选项：");
			}
		}
		input.close();
	}

	private static void handleUserActions(User user, Scanner input) {
		if (user instanceof Student) {
			Student student = (Student) user;
			GradeManager gradeManager = new GradeManager(student.getScore(), UserStorage.getInstance()); // 创建成绩管理器实例
			System.out.println("请输入学生ID：");
			String studentID = input.next();
			gradeManager.performActions(input, studentID); // 执行成绩管理操作
		} else {
			System.out.println("未知用户类型！");
		}
	}
}

class UserStorage {
	private Map<String, Score> scoreTable;
	private Map<String, User> usersMap;
	private static UserStorage instance;

	private UserStorage() {
		this.usersMap = new HashMap<>();
	}

	public static UserStorage getInstance() {
		if (instance == null) {
			instance = new UserStorage();
		}
		return instance;
	}

	public User login(String username, String password) {
		User user = usersMap.get(username);
		if (user != null && user.getPassword().equals(password)) {
			return user;
		} else {
			return null;
		}
	}

	public void registerUser(User newUser) {
		usersMap.put(newUser.getUsername(), newUser);
	}

	public Map<String, User> getUsers() {
		// TODO Auto-generated method stub
		return null;
	}

	// 获取指定学生ID的学生信息
	public Student getStudentById(String studentID) {
		User user = usersMap.get(studentID);
		if (user instanceof Student) {
			return (Student) user;
		} else {
			return null;
		}
	}

	public Score getScoreByStudentID(String studentID) {
		// 假设scoreTable是一个存储学生ID和成绩信息的数据库表
		// 这里假设有一个名为findScoreByStudentID的数据库查询方法用于从数据库中查找成绩信息
		Score score = scoreTable.get(studentID);
		return score;
	}
}

abstract class User {
	private String username;
	private String password;
	private String personID;
	private String phoneNumber;

	public User(String username, String password, String personID, String phoneNumber) {
		this.username = username;
		this.password = password;
		this.personID = personID;
		this.phoneNumber = phoneNumber;
	}

	public String getUsername() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	public abstract Score getScore();
}

class Student extends User {

	private Score score;

	public Student(String username, String password, String personID, String phoneNumber) {
		super(username, password, personID, phoneNumber);
		this.score = new Score(personID, username, 0);
	}

	@Override
	public Score getScore() {
		return score;
	}
}

class Score {
	private String studentID;
	private String studentName;
	private int studentNumber;
	private String courseName;
	private int score;
	private Map<String, Integer> courseGrades = new HashMap<>();

	public void addCourseGrade(String course, int grade) {
		courseGrades.put(course, grade);
	}

	public Score(String studentID, String studentName, int studentNumber) {
		this.studentID = studentID;
		this.studentName = studentName;
		this.studentNumber = studentNumber;
		this.courseGrades = new HashMap<>();
	}

	// 构造函数
	public Score(String courseName, int score) {
		this.courseName = courseName;
		this.score = score;
	}

	// 获取课程名称
	public String getCourseName() {
		return courseName;
	}

	// 设置课程名称
	public void setCourseName(String courseName) {
		this.courseName = courseName;
	}

	// 获取分数
	public int getScore() {
		return score;
	}

	// 设置分数
	public void setScore(int score) {
		this.score = score;
	}

	public void setGrade(String course, int grade) {
		courseGrades.put(course, grade);
	}

	public void addGrade(String course, int grade) {
		courseGrades.put(course, grade);
	}

	public int getGrade(String course) {
		return courseGrades.getOrDefault(course, 0);
	}

	public void removeGrade(String course) {
		courseGrades.remove(course);
	}

	public Map<String, Integer> getGrades() {
		return courseGrades;
	}

	public int getTotalScore() {
		int sum = 0;
		for (int grade : courseGrades.values()) {
			sum += grade;
		}
		return sum;
	}

	// 查看学生成绩单
	public void viewAllGrades() {
		System.out.println("学生的所有成绩如下：");
		for (Map.Entry<String, Integer> entry : courseGrades.entrySet()) {
			System.out.println(entry.getKey() + ": " + entry.getValue());
		}
	}

	public void statisticsGrades() {
		double sum = 0;
		int max = Integer.MIN_VALUE;
		int min = Integer.MAX_VALUE;
		for (int grade : courseGrades.values()) {
			sum += grade;
			if (grade > max) {
				max = grade;
			}
			if (grade < min) {
				min = grade;
			}
		}
		double average = sum / courseGrades.size();
		System.out.println("学生所有成绩的统计信息如下：");
		System.out.println("平均成绩：" + average);
		System.out.println("最高成绩：" + max);
		System.out.println("最低成绩：" + min);
	}

	// 添加成绩
	private void addGrades(Scanner input) {
		System.out.print("请输入学生ID：");
		String studentID = input.next();
		// 根据学生ID获取学生成绩信息
		Score studentScore = UserStorage.getInstance().getScoreByStudentID(studentID);
		if (studentScore != null) {
			System.out.print("请输入课程名称：");
			String course = input.next();
			System.out.print("请输入成绩：");
			int grade = input.nextInt();
			// 将课程成绩信息存储到学生成绩信息中
			studentScore.addCourseGrade(course, grade);
			System.out.println("成绩添加成功！");
		} else {
			System.out.println("学生ID无效，请重新输入！");
		}
	}

	// 修改学生成绩
	public void updateGrade(String course, int grade) {
		if (courseGrades.containsKey(course)) {
			courseGrades.put(course, grade);
		} else {
			System.out.println("该课程不存在！");
		}
	}

	// 删除学生成绩
	public void deleteGrade(String course) {
		if (courseGrades.containsKey(course)) {
			courseGrades.remove(course);
		} else {
			System.out.println("该课程不存在！");
		}
	}

	// 统计某门课平均分、最高分和最低分
	public void statisticsForCourse(String course) {
		List<Integer> gradesForCourse = new ArrayList<>();
		for (Map.Entry<String, Integer> entry : courseGrades.entrySet()) {
			if (entry.getKey().equals(course)) {
				gradesForCourse.add(entry.getValue());
			}
		}
		if (!gradesForCourse.isEmpty()) {
			double sum = 0;
			int max = Integer.MIN_VALUE;
			int min = Integer.MAX_VALUE;
			for (int grade : gradesForCourse) {
				sum += grade;
				if (grade > max) {
					max = grade;
				}
				if (grade < min) {
					min = grade;
				}
			}
			double average = sum / gradesForCourse.size();
			System.out.println("课程 " + course + " 的统计信息如下：");
			System.out.println("平均成绩：" + average);
			System.out.println("最高成绩：" + max);
			System.out.println("最低成绩：" + min);
		} else {
			System.out.println("该课程暂无成绩记录！");
		}
	}

	// 修改 Score 类中的 findStudentGrades 方法
	public Map<String, Integer> findStudentGrades(String studentID) {
		return courseGrades;
	}

	// 按成绩从高往低排序，并输出
	public void sortGradesDescending() {
		Map<String, Integer> sortedGrades = courseGrades.entrySet().stream()
				.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
				.collect(LinkedHashMap::new, (map, entry) -> map.put(entry.getKey(), entry.getValue()), Map::putAll);

		System.out.println("按成绩从高往低排序后的成绩如下：");
		for (Map.Entry<String, Integer> entry : sortedGrades.entrySet()) {
			System.out.println(entry.getKey() + ": " + entry.getValue());
		}
	}
}

class GradeManager {
	private Score score;
	private UserStorage userStorage;

	public GradeManager(Score score, UserStorage userStorage) {
		this.score = score;
		this.userStorage = userStorage;
	}

	public void performActions(Scanner input, String studentID) {
		Student student = userStorage.getStudentById(studentID);
		if (student != null) {
			score = student.getScore(); // 更新成绩对象为学生的成绩
			// 执行成绩管理操作
			boolean exit = false;
			while (!exit) {
				System.out.println("==============================");
				System.out.println("===== 欢迎进入成绩管理页面 =====");
				System.out.println("===== 1. 查看成绩 =====");
				System.out.println("===== 2. 修改成绩 =====");
				System.out.println("===== 3. 添加成绩 =====");
				System.out.println("===== 4. 删除成绩 =====");
				System.out.println("===== 5. 查找学生的课程成绩 =====");
				System.out.println("===== 6. 统计课程成绩 =====");
				System.out.println("===== 7. 排序所有课程的成绩 =====");
				System.out.println("===== 8. 查找学生成绩 =====");
				System.out.println("===== 0. 退出成绩管理页面 =====");
				System.out.println("*****根据以上的选项，请选择您的操作：***");
				System.out.println("==============================");

				int choice = 0;

				while (true) {
					try {
						System.out.print("请输入选项（0-7）：");
						choice = input.nextInt();
						if (choice < 0 || choice > 7) {
							throw new IllegalArgumentException();
						}
						break;
					} catch (InputMismatchException e) {
						System.out.println("输入无效，请重新输入选项：");
						input.nextLine();
					} catch (IllegalArgumentException e) {
						System.out.println("选项无效，请重新输入选项：");
						input.nextLine();
					}
				}

				switch (choice) {
				case 1:
					// 查看成绩
					score.viewAllGrades();
					break;
				case 2:
					// 修改成绩
					modifyGrade(input);
					break;
				case 3:
					// 添加成绩
					addGrades(input);
					break;
				case 4:
					// 删除成绩
					deleteGrade(input);
					break;
				case 5:
					// 查找学生的课程成绩
					selectGrades(input);
					break;
				case 6:
					// 统计课程成绩
					score.statisticsGrades();
					break;
				case 7:
					// 排序所有课程的成绩
					score.sortGradesDescending();
					break;
				case 8:
					// 查找学生成绩
					findStudentGrades(input);
					break;

				case 0:
					exit = true;
					System.out.println("退出系统！");
					break;
				default:
					System.out.println("选项无效，请重新输入选项：");
					break;
				}
			}
		} else {
			System.out.println("学生ID无效，请重新输入！");
		}
	}

	// 添加成绩
	private void addGrades(Scanner input) {
		System.out.print("请输入学生ID：");
		String studentID = input.next();
		// 根据学生ID获取学生成绩信息
		Score studentScore = UserStorage.getInstance().getScoreByStudentID(studentID);
		if (studentScore != null) {
			System.out.print("请输入课程名称：");
			String course = input.next();
			System.out.print("请输入成绩：");
			int grade = input.nextInt();
			// 将课程成绩信息存储到学生成绩信息中
			studentScore.addGrade(course, grade); // Using the addGrade method
			System.out.println("成绩添加成功！");
		} else {
			System.out.println("学生ID无效，请重新输入！");
		}
	}

	// 修改成绩
	private void modifyGrade(Scanner input) {
		System.out.print("请输入要修改成绩的课程名称：");
		String course = input.next();
		System.out.print("请输入新的成绩：");
		int grade = input.nextInt();
		score.updateGrade(course, grade);
		System.out.println("成绩修改成功！");
	}

	// 删除成绩
	private void deleteGrade(Scanner input) {
		System.out.print("请输入要删除成绩的课程名称：");
		String course = input.next();
		score.deleteGrade(course);
		System.out.println("成绩删除成功！");
	}

	// 修改成绩管理器 GradeManager 类中的 selectGrades 方法
	private void selectGrades(Scanner input) {
		System.out.print("请输入要查找成绩的课程名称：");
		String course = input.next();
		int grade = score.getGrade(course);
		System.out.println("课程 " + course + " 的成绩为：" + grade);
		System.out.print("请输入学生ID：");
		String studentID = input.next();
		Score studentScore = UserStorage.getInstance().getScoreByStudentID(studentID);
		if (studentScore != null) {
			// Select grades from the retrieved score
		} else {
			System.out.println("学生ID无效，请重新输入！");
		}
	}

	// 查找学生成绩
	private void findStudentGrades(Scanner input) {
		System.out.print("请输入学生ID：");
		String studentID = input.next();
		score.findStudentGrades(studentID);
	}
}

class LoggedInUser {
	private Score score;
	private UserStorage userStorage;

	public LoggedInUser(Score score, UserStorage userStorage) {
		this.score = score;
		this.userStorage = userStorage;
	}

	public void manageGrades(Scanner input) {
		System.out.print("请输入学生ID：");
		String studentID = input.nextLine();
		GradeManager gradeManager = new GradeManager(score, userStorage);
		gradeManager.performActions(input, studentID);
	}
}
